package server_commands;

import static server.RLM_Server.activeConnections;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;

import server.ServerSocketConnection;
import utils.GenerateID;
import connection_modul.DatabaseConnection;

public class ADD_USERCommand extends Command {
	
	public ADD_USERCommand(String parameter) {
		setCode(ADD_CMD);
		setParameter(parameter);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	/**
	 * Metoda koja vrsi dodavanje trazenog korisnika u kontakt listu onoga ko 
	 * je trazio. Ukoliko je korisnik, koga treba dodati na listu, offline, 
	 */
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {
		
		StringTokenizer tokenizer = new StringTokenizer(getParameter());
		
		String username = tokenizer.nextToken();
		String addingContact = tokenizer.nextToken();
		
		
		String SQLQuery = "SELECT tblUsers.username " +
						  "FROM tblUsers " +
						  "WHERE tblUsers.username = '" + addingContact + "'";

		dbConnection.clearDataStore();
		
		try {
			dbConnection.doStatement(SQLQuery);
		
			if (dbConnection.data.size() == 0) {
				connection.setMessage("200 User does not exist!");
				dbConnection.doCommit();
				return false;
			}
			
			
			SQLQuery = "SELECT * FROM tblContacts" +
			" WHERE tblContacts.user_source = '" + username + "' AND" +
				" tblContacts.user_dest = '" + addingContact + "'";
	
			
			dbConnection.clearDataStore();
			
	
			dbConnection.doStatement(SQLQuery);
			
			if (dbConnection.data.size() != 0) {
				connection.setMessage("200 User already added!");
				dbConnection.doCommit();
				return false;
			}
	
			dbConnection.clearDataStore();
			
			// dodavanje novog korisnika u bazu
			String addUserQuery = "INSERT INTO tblContacts (contact_id, user_source, user_dest)" +
					" VALUES(" + GenerateID.generateID() + ", '" + username + "', '" + addingContact + "')";
			
			dbConnection.doUpdateStatement(addUserQuery);
			
			dbConnection.clearDataStore();
			
			SQLQuery = "SELECT * FROM tblBlocks" +
				" WHERE tblBlocks.user_source = '" + username + "' AND" +
					" tblBlocks.user_dest = '" + addingContact + "'";
			
			// proverava se da li je korisnik koga treba obavestiti blokiran
			
			dbConnection.doStatement(SQLQuery);
			
			
			ArrayList<Vector> blockingList = new ArrayList<Vector>(dbConnection.data);	
			
			dbConnection.clearDataStore();
			
			SQLQuery = "SELECT * FROM tblContacts" +
			" WHERE tblContacts.user_source = '" + addingContact + "' AND" +
				" tblContacts.user_dest = '" + username + "'";
	
		
			dbConnection.doStatement(SQLQuery);
		
			
			ArrayList<Vector> contactList = new ArrayList<Vector>(dbConnection.data);	
			
			dbConnection.clearDataStore();
	
			ServerSocketConnection addingClientConnection = activeConnections.get(addingContact);
			
			// prvi scenario; ukoliko je korisnik online		
			if( addingClientConnection != null ) {
				// dodati korisnik nije u blok listi
				if( blockingList.size() == 0 && contactList.size() == 0 ) {
					
					SQLQuery = "SELECT tblUsers.username, tblUsers.nickname, tblUsers.email, tblUsers.ip_address, tblUsers.local_address, tblUsers.port, tblUsers.status, tblUsers.reg_date, tblUsers.avatar " +
							   "FROM tblUsers " +
							   "WHERE tblUsers.username = '" + username + "'";
					
					dbConnection.doStatement(SQLQuery);
						
					if (dbConnection.data.size() == 0) {
						connection.setMessage("200 User does not exist!");
						dbConnection.doCommit();
						return false;
					}
					
					Vector row = new Vector(dbConnection.data.get(0));
					
					StringBuffer message = new StringBuffer();
					
					message.append("SERV_ADDED ");
					message.append(addingContact);
					message.append(" ");
					for (int i = 0; i < row.size(); i++) {
						message.append(row.get(i).toString());
						
						if (i < row.size() - 1) {
							message.append(" ");
						}
					}
					
					String completedMessage = message.toString();
					
					addingClientConnection.setMessage(completedMessage);
				}
			}
			
			// ukoliko je korisnik koga treba obavestiti offline
			else {
				// TODO upisuje se offline poruka u bazu koja obavestava korisnika pri logovanju
				
				if ( blockingList.size() == 0 && contactList.size() == 0 ) {
	
					String SQLUpdate = "INSERT INTO tblOffActivities (off_id, username, add_message)" +
							" VALUES (" + GenerateID.generateID() + ", '" + addingContact + "', '" + username + "')";
					
					dbConnection.doUpdateStatement(SQLUpdate);
				}
				
				// inace, korisnik je blokiran i ne treba ga obavestiti.			
			}
			
			connection.setMessage("100 User added.");
		
		} catch (SQLException e) {
			e.printStackTrace();
			dbConnection.doRollBack();
			return false;
		}
		
		dbConnection.doCommit();
		return true;
	}
}
